package com.cn.jdia.mq.test;

import java.util.List;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MqUtils {

	private static String brokerURL = "tcp://172.20.5.121:61616";
	private static transient ConnectionFactory factory;
	private transient static Connection connection;
	private transient static Session session;
	private transient static MessageProducer producer;

	private static MqUtils mqUtils;
	
	public static MqUtils getInstance(){
		if(mqUtils==null){
			mqUtils=new MqUtils();
			mqUtils.initMq();
		}
		return mqUtils;
	}
	
	public void initMq(){
		factory = new ActiveMQConnectionFactory(brokerURL);
	}
	
	public void sendMessage(String topic, List<String> queue) throws JMSException {
		connection = factory.createConnection();
		connection.start();
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		producer = session.createProducer(null);

		Destination destination = session.createTopic(topic);
		Message message;
		
		for(String xml:queue){
			message = session.createTextMessage(xml);
			producer.send(destination, message);
		}
		
		connection.stop();
		connection.close();
	}
}
